<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="">
        <el-breadcrumb-item>
          <div class="div1">商品管理</div>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <div class="div2">商品属性库</div>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 面包屑导航 default-expand-all -->
    <div class="headerbox">
      <div class="header">
        <div class="title_left"></div>
        商品属性库
      </div>
      <div class="headerbox_right">
        <!-- <el-button size="mini" type="primary" @click="refresh()"
          >刷新</el-button
        > -->
        <!-- <el-button size="mini" @click="back()">返回</el-button> -->
      </div>
    </div>
    <div class="box">
      <div class="el-menu-input">
        <div class="titleBox">
          <div style="display: flex; align-items: center">
            <div class="left_title">选择类目</div>
          </div>
          <!-- <i
            style="cursor: pointer"
            class="el-icon-refresh"
            @click="treeAxios"
          ></i> -->
        </div>
        <el-input placeholder="输入关键字进行过滤" v-model.trim="filterText">
        </el-input>

        <el-tree
          ref="tree"
          class="filter-tree"
          :data="categoryOptions"
          :props="{
            label: 'categoryName',
            value: 'id',
          }"
          :highlight-current="true"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        >
        </el-tree>
      </div>
      <div class="inquiryTab">
        <div class="titleBox">
          <div class="left_title">
            <span v-if="categoryName.length == 3">
              已选择：<span style="color: #333333; font-size: 16px"
                >{{ categoryName[0] }}<span v-if="categoryName[1]">></span
                >{{ categoryName[1] }}<span v-if="categoryName[2]">></span
                >{{ categoryName[2] }}</span
              ><span style="color: #999999; font-size: 16px"
                >(共{{ categoryLength }}个属性组{{ categoryNum }}个属性)</span
              >
            </span>
          </div>
          <div>
            <el-button
              type="primary"
              style="width: 120px; height: 36px; line-height: 10px"
              v-if="parArray.indexOf('addAttributeSet') != -1"
              @click="addAttributeset('addAttributeset')"
              >新增属性组</el-button
            >
          </div>
        </div>
        <div class="table">
          <el-table
            border
			v-loading="loading"
            :header-cell-style="{ background: '#f8f8f8' }"
            :data="tableData"
            style="width: 100%"
            align="center"
            :span-method="objectSpanMethod"
            @cell-mouse-enter="cellMouseEnter"
            @cell-mouse-leave="cellMouseLeave"
            :row-class-name="tableRowClassName"
          >
            <el-table-column type="index" label="序号" width="60">
            </el-table-column>
            <el-table-column label="属性组名" prop="propName">
              <template slot-scope="props">{{ props.row.propName }}</template>
            </el-table-column>
            <el-table-column label="属性名称" prop="name">
              <template slot-scope="props">{{ props.row.name }}</template>
            </el-table-column>
            <el-table-column label="类型" prop="typeFlagLabel">
              <!-- <template slot-scope="props">{{
                props.row.typeFlagLabel
              }}</template> -->
            </el-table-column>
            <el-table-column label="必填" prop="requiredFlagLabel">
              <!-- <template slot-scope="props">{{
                props.row.requiredFlagLabel
              }}</template> -->
            </el-table-column>
            <el-table-column label="关键属性" prop="mainFlagLabel">
              <!-- <template slot-scope="props">{{
                props.row.mainFlagLabel
              }}</template> -->
            </el-table-column>
            <el-table-column label="属性值" prop="itemLabels">
              <template slot-scope="props">{{ props.row.itemLabels }}</template>
            </el-table-column>
            <el-table-column label="状态" prop="statusLabel" width="80">
              <template slot-scope="props">
                <p
                  :style="
                    props.row.status == '1' ? 'color:#67C23A' : 'color:#F56C6C'
                  "
                >
                  {{ props.row.statusLabel }}
                </p>
              </template>
            </el-table-column>
            <el-table-column label="属性操作" width="190">
              <template slot-scope="props">
                <el-button
                  type="text"
                  v-if="
                    props.row.firstFlag == 0 &&
                    parArray.indexOf('propertymove') != -1
                  "
                  @click="propertyMoveup(props.row)"
                  >上移{{ props.index }}</el-button
                >
                <el-button
                  type="text"
                  v-if="
                    props.row.lastFlag == 0 &&
                    parArray.indexOf('propertydown') != -1
                  "
                  @click="propertyMovedown(props.row)"
                  >下移</el-button
                >
                <el-button
                  type="text"
                  @click="propertyEdit('propertyEdit', props.row)"
                  v-if="parArray.indexOf('propertyedit') != -1 && props.row.id"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  style="color: #f56c6c"
                  v-if="
                    parArray.indexOf('propertydelete') != -1 && props.row.id
                  "
                  @click="categoryDelete(props.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
            <el-table-column label="属性组操作" width="250">
              <template slot-scope="props">
                <el-button
                  v-if="
                    props.row.groupfirst == 0 &&
                    parArray.indexOf('moveAttributeset') != -1
                  "
                  type="text"
                  @click="attributesetMoveup(props.row)"
                  >上移</el-button
                >
                <el-button
                  @click="attributesetMovedown(props.row)"
                  v-if="
                    props.row.grouplast == 0 &&
                    parArray.indexOf('downAttributeSet') != -1
                  "
                  type="text"
                  >下移</el-button
                >
                <el-button
                  type="text"
                  @click="propertyEdit('add', props.row)"
                  v-if="parArray.indexOf('addproperty') != -1"
                  >添加属性</el-button
                >
                <el-button
                  type="text"
                  @click="addAttributeset('edit', props.row)"
                  v-if="parArray.indexOf('editAttributeSet') != -1"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  style="color: #f56c6c"
                  v-if="parArray.indexOf('deleteAttributeSet') != -1"
                  @click="categoryGroupDelete(props.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!--                                弹框                                       -->
      <el-dialog
        :title="dialog.title"
        :visible.sync="dialog.visible"
        :width="dialog.width"
        :before-close="handleClose"
        append-to-body
      >
        <template v-if="dialog.type == 'propertyEdit' || dialog.type == 'add'">
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="属性名称" prop="name" label-width="85px">
              <el-input
                placeholder="请输入属性名称"
                v-model.trim="ruleForm.name"
                :maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="属性类型" prop="typeFlag" label-width="85px">
              <el-select
                style="width: 100%"
                v-model="ruleForm.typeFlag"
                clearable
                placeholder="商品维护时内容录入方式：当选中项为单选、复选时需要填写对应属性值"
                @change="hangleTypeFlag"
              >
                <el-option
                  v-for="item in dictionaries.goods_attr_type"
                  :key="item.dictId"
                  :label="item.dictName"
                  :value="item.dictId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="必填" prop="requiredFlag" label-width="85px">
              <el-radio-group
                v-model="ruleForm.requiredFlag"
                style="margin-left: 4px"
              >
                <el-radio label="1">是</el-radio>
                <el-radio label="0" style="margin-left: 20px">否</el-radio>
              </el-radio-group>
              <span class="hint">商品维护时内容是否必填</span>
            </el-form-item>
            <el-form-item label="关键属性" prop="mainFlag" label-width="85px">
              <el-radio-group
                v-model="ruleForm.mainFlag"
                style="margin-left: 4px"
              >
                <el-radio label="1">是</el-radio>
                <el-radio label="0" style="margin-left: 20px">否</el-radio>
              </el-radio-group>
              <span class="hint">当前属性是否关键属性</span>
            </el-form-item>
            <el-form-item label="状态" prop="status" label-width="85px">
              <el-radio-group
                v-model="ruleForm.status"
                v-for="item in dictionaries.enable_status"
                :key="item.dictId"
              >
                <el-radio
                  style="padding-right: 19px; padding-left: 4px"
                  :label="item.dictId"
                  >{{ item.dictName }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark" label-width="85px">
              <el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="ruleForm.remark"
                :maxlength="200"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item
              label="属性值"
              v-if="TypeFlagValue != 1 && TypeFlagValue != 4"
              :prop="propertyDataState"
              label-width="85px"
            >
              <el-table
                class="dialogTabel"
                :data="ruleForm.propertyData"
                :header-cell-style="{
                  background: '#f8f8f8',
                  fontSize: '14px',
                  color: '#606266',
                }"
                style="width: 100%"
              >
                <el-table-column type="index" label="序号" width="70">
                </el-table-column>
                <el-table-column label="属性值" prop="label">
                  <template slot-scope="props">
                    <el-input
                      v-model.trim="props.row.label"
                      placeholder="请输入内容"
                      ref="addPropertyInput"
                      @keyup.native.13="addProperty(props.$index)"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="属性操作" prop="name">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      @click="upMove(scope.$index, scope.row)"
                      >上移</el-button
                    >
                    <el-button
                      type="text"
                      @click="upDown(scope.$index, scope.row)"
                      >下移</el-button
                    >
                    <el-button
                      type="text"
                      style="color: #f56c6c"
                      @click="rowDelete(scope.$index, scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
              <div class="addProperty">
                <el-button type="text" icon="el-icon-plus" @click="addProperty"
                  >新增</el-button
                >
              </div>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialog.visible = false">取 消</el-button>
            <el-button type="primary" @click="submit('ruleForm')"
              >确 定</el-button
            >
          </span>
        </template>
        <template
          v-if="dialog.type == 'addAttributeset' || dialog.type == 'edit'"
          class="demo-ruleForm"
        >
          <el-form
            :model="propertyForm"
            :rules="addRules"
            ref="propertyForm"
            label-width="100px"
          >
            <el-form-item label="属性组名称" prop="name">
              <el-input
                placeholder="请输入属性组名称"
                v-model.trim="propertyForm.name"
                :maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="所属类目" prop="categoryId">
              <el-cascader
                placeholder="请选择三级类目"
                :disabled="categoryState"
                style="width: 100%"
                v-model="propertyForm.categoryId"
                :options="categoryOptions"
                :props="{
                  label: 'categoryName',
                  value: 'id',
                  checkStrictly: true,
                }"
                filterable
                clearable
                @change="handleCategory"
              ></el-cascader>
            </el-form-item>
            <el-form-item class="attributeSet">
              <el-button class="cancel" @click="dialog.visible = false"
                >取 消</el-button
              >
              <el-button
                class="confirm"
                type="primary"
                @click="attributesetSubmit('propertyForm')"
                >确 定</el-button
              >
            </el-form-item>
          </el-form>
        </template>
      </el-dialog>

      <!--                                弹框                                       -->
      <el-dialog
        title="删除属性组"
        :visible.sync="dialogVisible"
        width="520px"
        :before-close="handledeleteClose"
        append-to-body
        class="deletegroup"
      >
        <div
          slot="title"
          class="header-title"
          style="display: flex; align-items: center"
        >
          <span style="font-size: 28px; color: red"
            ><i class="el-icon-warning"></i
          ></span>
          <span style="padding-left: 12px; font-size: 22px">删除属性组</span>
        </div>
        <span style="font-size: 16px; color: #333333"
          >此操作将删除选中属性组，是否继续？</span
        >
        <div style="font-size: 12px; color: #999999; padding-top: 5px">
          注：属性组内所包含的属性页一并删除
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button
            @click="dialogVisible = false"
            style="
              width: 120px;
              height: 36px;
              border: 1px solid #d9d9d9;
              opacity: 1;
              line-height: 2px;
              border-radius: 4px;
            "
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="deleteGroup"
            style="
              width: 120px;
              height: 36px;
              line-height: 2px;
              opacity: 1;
              border-radius: 4px;
            "
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val);
    },
    tableData () {
      this.merage()
    }
  },
  data () {
    return {
      filterText: "",
      categoryOptions: [],
      dialogVisible: false,
      formInline: {
        name: "",
      },
      departmentList: [],
      tableData: [],
	  loading:false,
      dialog: { visible: false, title: "", type: "", width: "" },
      propName: [],
      form: {
        id: "",//	int	主键id
        name: '',//	string	属性名称
        typeFlag: "",//	string	类型
        typeFlagLabel: "",//	string	类型显示值
        requiredFlag: "",//	string	是否必填
        requiredFlagLabel: "",//	string	必填显示值
        mainFlagLabel: "",//	string	关键属性
        itemLabels: "",//	string	属性值
        itemList: "",//	string	属性值明细
        status: "",//	string	状态
        statusLabel: "",//	string	状态（字典分组：enable_status）
      },
      ruleForm: {
        id: "",//	是	int	主键id
        name: "",//	是	string	属性名称
        typeFlag: "",//	是	string	属性类型（字典：goods_attr_type）
        requiredFlag: "",//	是	string	是否必填（0否；1是）
        mainFlag: "",//	是	int	是否关键属性（0否；1是）
        status: "",//	是	string	状态（字典分组：enable_status）
        remark: "",//	否	string	备注
        itemList: "",//	是	object[]	属性值列表
        lable: "",//属性值内容
        propertyData: [],//编辑属性弹窗内属性值

      },
      propertyDataState: "propertyData",
      propertyForm: {
        name: '',//	是	string	属性组名称
        categoryId: "",//	是	string	类目id
      },
      TypeFlagValue: "",//属性类型值

      // 已选值显示
      categoryName: "",
      categoryLength: "",
      categoryNum: "",
      // 已选值显示结束
      dataId: "",//类目的ID
      rules: {
        name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        typeFlag: [
          { required: true, message: '请选择属性类型', trigger: 'change' }
        ],
        requiredFlag: [
          { required: true, message: '请选择是否必填', trigger: 'change' }
        ],
        mainFlag: [
          { required: true, message: '请选择是否关键属性', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        propertyData: [
          { required: true, message: '请填写属性值', trigger: 'blur' }
        ]
      },
      addRules: {
        name: [
          { required: true, message: '请输入属性组名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择类目', trigger: 'change' }
        ],
      },
      dictionaries: { // 字典数据
        goods_attr_type: [], // 属性类型
        enable_status: [],//状态
      },
      groupRow: "",//用来存放属性组row数据
      propId: "",//属性组ID
      propertyId: "",//属性id
      categoryState: false,


      orgName: "",
      id: "",
      data: "",
      if_code: true,
      limits: "",
      parArray: [],
      pageSize: 10,
      pageNo: 1,
      orgCode: "",
      dictionariesList: [],//数据字典
      orgtype: "4",//组织类型ID

      typeNameArr: [],  // 第一列进行合并操作时存放的数组变量
      typeNamePos: 0, // 上面的数组的下标值
      storeArr: [],  // 第二列进行合并操作时存放的数组变量
      storePos: 0,// 上面的数组的下标值
      feeArr: [], // 第三列进行合并操作时存放的数组变量
      feePos: 0,// 上面的数组的下标值
      rowIndex: '-1',
      OrderIndexArr: [],
      hoverOrderArr: []
    }
  },
  created () {
    console.log(this.$route)

    this.getCategoryDate()
    // this.getDataList()
    // 获取字典数据
    for (let type in this.dictionaries) { this.getDictionaries(type) }
    // this.objectSpanMethod()
    // 权限设定判断
    this.limits = JSON.parse(sessionStorage.getItem('limit'));
    const params = this.limits.buttonTreeDto.filter(item => item.menuCode === "goodsPropertyCode");
    params[0].buttonList.forEach((item) => {
      this.parArray.push(item.code)
    })
    console.log(this.parArray)
    // 权限设定判断
  },
  mounted () {
    this.merage()
  },
  methods: {
    merageInit () { // 在下文的时候会用到，对数据进行初始化是很有必要的
      this.typeNameArr = [];
      this.typeNamePos = 0;
      this.storeArr = [];
      this.storePos = 0;
      this.feeArr = [];
      this.feePos = 0;
    },
    merage () {
      this.merageInit()// 前文的初始化数据函数
      for (let i = 0; i < this.tableData.length; i += 1) {

        if (i == 0) {
          // 第一行必须存在
          this.typeNameArr.push(1);
          this.typeNamePos = 0;
          this.storeArr.push(1);
          this.storePos = 0;
          this.feeArr.push(1);
          this.feePos = 0;

        } else {
          // 判断当前元素与上一个元素是否相同,eg：this.typeNamePos 是 this.typeNameArr序号
          // 第一列 下面的是eslint的不限制语法
          // eslint-disable-next-line no-lonely-if
          if (this.tableData[i].propName == this.tableData[i - 1].propName) {
            this.typeNameArr[this.typeNamePos] += 1;
            this.typeNameArr.push(0);
          } else {
            this.typeNameArr.push(1);
            this.typeNamePos = i;
          }
        }
      }
      var OrderObj = {}
      this.tableData.forEach((element, index) => {
        element.rowIndex = index
        if (OrderObj[element.propName]) {
          OrderObj[element.propName].push(index)
        } else {
          OrderObj[element.propName] = []
          OrderObj[element.propName].push(index)
        }
      })

      for (var k in OrderObj) {
        if (OrderObj[k].length > 1) {
          this.OrderIndexArr.push(OrderObj[k])
        }
      }
    },
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1 || columnIndex === 9) {
        // 第一列的合并方法
        const row1 = this.typeNameArr[rowIndex];
        const col1 = row1 > 0 ? 1 : 0; // 如果被合并了row = 0; 则他这个列需要取消
        return {
          rowspan: row1,
          colspan: col1,
        };

      }
    },
    // 合并表格后hover样式
    tableRowClassName ({ row, rowIndex }) {
      var arr = this.hoverOrderArr
      for (var i = 0; i < arr.length; i++) {
        if (rowIndex === arr[i]) {
          return 'success-row'
        }
      }

    },
    cellMouseEnter (row, column, cell, event) {
      this.rowIndex = row.rowIndex
      this.hoverOrderArr = []
      this.OrderIndexArr.forEach((element) => {
        if (element.indexOf(this.rowIndex) >= 0) {
          this.hoverOrderArr = element
        }
      })
    },
    cellMouseLeave (row, column, cell, event) {
      this.rowIndex = '-1'
      this.hoverOrderArr = []
    },
    // 合并表格后hover样式结束
    // 获取列表数据
    getDataList (categoryId) {
		this.loading = true;
      const params = {
        categoryId: categoryId ? categoryId : ""
      }
      this.categoryNum = 0
      this.$api.goodsAttrListByCategoryId(params).then((res) => {
        console.log(res, "res")
        if (res.code == 0) {
          let data = []
          this.categoryLength = res.data.length
          res.data.forEach(e => {
            this.categoryNum = Number(this.categoryNum) + Number(e.itemList.length)
            if (e.itemList.length == 0) {
              e.itemList.push({})
            }
            e.itemList.forEach(i => {
              i.propId = e.id
              i.propName = e.name
              i.groupfirst = e.firstFlag
              i.grouplast = e.lastFlag
              data.push(i)
            })
          });
          console.log(this.categoryNum, "this.categoryNum")
          this.tableData = data
          console.log(data, "this.tableData")
          this.merage()
        }
		this.loading = false;
      }).catch((err) => { 
		  console.log(err) 
		  this.loading = false;
	  })
    },
    // 类目点击获取列表数据
    handleNodeClick (data) {
      this.dataId = data.id
      this.propName = []
      console.log(data, "类目点击获取列表数据");
      this.getDataList(data.id)
      let arr = []
      arr = data.path.split('-')
      arr.forEach(res => {
        if (res) {
          this.propName.push(res)
        }

      })
      console.log(this.propName, "resrersere")
      let arrData = []
      const categoryOptions = this.categoryOptions
      categoryOptions.forEach(firstItem => {

        this.propName.forEach((res) => {
          console.log(res, "resers")
          if (firstItem.id == res) {
            arrData.push(firstItem.categoryName)
            return
          }
          if (firstItem.children) {
            firstItem.children.forEach(secondItem => {
              if (secondItem.id == res) {
                // arrData.push(firstItem.categoryName)
                arrData.push(secondItem.categoryName)
                return
              }
              if (secondItem.children) {
                secondItem.children.forEach(thirdItem => {
                  if (thirdItem.id == res) {
                    // arrData.push(firstItem.categoryName)
                    // arrData.push(secondItem.categoryName)
                    arrData.push(thirdItem.categoryName)
                    return
                  }
                })
              }
            })
          }
        })
      })
      console.log(arrData, "arrData")
      this.categoryName = arrData
      console.log(this.categoryName, "this.categoryName")
    },

    filterNode (value, categoryOptions) {
      if (!value) return true;
      return categoryOptions.label.indexOf(value) !== -1;
    },
    // 属性上移
    propertyMoveup (row) {
      const data = {
        id: row.id
      }
      this.$api.goodsAttrSortUp(data).then((res) => {
        if (res.code == 0) {
          this.$message.success('操作成功！')
          this.getDataList(this.dataId)
        }
      }).catch(err => { console.log(err) })
    },
    // 属性下移
    propertyMovedown (row) {
      const data = {
        id: row.id
      }
      this.$api.goodsAttrSortDown(data).then((res) => {
        if (res.code == 0) {
          this.$message.success('操作成功！')
          this.getDataList(this.dataId)
        }
      }).catch(err => { console.log(err) })
    },
    // 属性组删除
    categoryGroupDelete (row) {
      this.dialogVisible = true
      this.groupRow = row
    },
    // 属性组删除弹框确定
    deleteGroup () {
      const data = {
        id: this.groupRow.propId
      }
      this.$api.goodsAttrSortGroupDelete(data).then(res => {
        if (res.code == 0) {
          this.$message.success("删除成功！")
          this.getDataList(this.dataId)
          this.dialogVisible = false

        }
      }).catch(err => { console.log(err) })
    },
    // 属性删除
    categoryDelete (row) {
      this.$confirm('此操作将删除选中属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row, "row")
        const data = {
          id: row.id,
        }
        this.$api.goodsAttrDelete(data).then(res => {
          if (res.code == 0) {
            this.$message.success("删除成功！")
            this.getDataList(this.dataId)
            this.dialog.visible = false
          }
        }).catch(err => { console.log(err) })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 弹框关闭
    handleClose () {
      this.dialog.visible = false;
    },
    handledeleteClose () {
      this.dialogVisible = false;
    },
    // 编辑属性
    propertyEdit (type, row) {
      if (type == 'propertyEdit') {
        console.log(row, "编辑row")
        this.dialog.title = '编辑属性'
        this.dialog.visible = true
        this.dialog.type = "propertyEdit"
        this.dialog.width = "580px"
        this.propertyId = row.id //属性id
        this.goodsAttrDetail(row.id)
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      } else {
        this.ruleForm = {
          id: "",//	是	int	主键id
          name: "",//	是	string	属性名称
          typeFlag: "",//	是	string	属性类型（字典：goods_attr_type）
          requiredFlag: "",//	是	string	是否必填（0否；1是）
          mainFlag: "",//	是	int	是否关键属性（0否；1是）
          status: "",//	是	string	状态（字典分组：enable_status）
          remark: "",//	否	string	备注
          itemList: "",//	是	object[]	属性值列表
          propertyData: [],
        }
        this.dialog.title = '新增属性'
        this.propId = row.propId//属性组id
        this.dialog.visible = true
        this.dialog.type = "add"
        this.dialog.width = "580px"
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }

    },
    goodsAttrDetail (id) {
      const params = {
        id: id
      }
      this.$api.goodsAttrDetail(params).then(res => {
        if (res.code == 0) {
          console.log(res, "ressssssss")
          this.ruleForm.name = res.data.name
          this.TypeFlagValue = res.data.typeFlag
          if (res.data.typeFlag == 1) {
            this.propertyDataState = 'State'
          } else {
            this.propertyDataState = 'propertyData'
          }
          this.ruleForm.typeFlag = res.data.typeFlag + ''
          this.ruleForm.requiredFlag = res.data.requiredFlag + ''
          this.ruleForm.mainFlag = res.data.mainFlag + ''
          this.ruleForm.status = res.data.status + ''
          this.ruleForm.remark = res.data.remark
          this.ruleForm.propertyData = res.data.itemList ? res.data.itemList : []
        }
      }).then(err => { console.log(err) })
    },
    // 编辑属性弹框内新增属性值
    addProperty (index) {
      console.log('新增-addProperty')
      const list = {
        id: "",
        label: "",
      };
      this.ruleForm.propertyData.push(list)//往数组前面新增
      // const addPropertyInput = `addPropertyInput${index}`
      this.$nextTick(() => {
        this.$refs.addPropertyInput.focus(); // 视图出现后使input获取焦点
      });
      // console.log(this.ruleForm.propertyData, "this.ruleForm.propertyData新增")
      // console.log(this.propertyDataState, "propertyDataState")
    },
    // 获取状态字典数据
    getDictionaries (type) {
      if (type && this.dictionaries[type].length > 0) { return }
      const params = { groupId: type }
      this.$api.dictionaries(params).then((res) => {
        console.log(res, "字典")
        this.dictionaries[type] = res.data
      }).catch((err) => {
        console.log(err)
      })
    },
    // 属性组上移
    attributesetMoveup (row) {
      const data = {
        id: row.propId
      }
      this.$api.goodsAttrSortGroupUp(data).then((res) => {
        if (res.code == 0) {
          this.$message.success('操作成功！')
          this.getDataList(this.dataId)
        }
      }).catch(err => { console.log(err) })
    },
    // 属性组下移
    attributesetMovedown (row) {
      const data = {
        id: row.propId
      }
      this.$api.goodsAttrSortGroupDown(data).then((res) => {
        if (res.code == 0) {
          this.$message.success('操作成功！')
          this.getDataList(this.dataId)
        }
      }).catch(err => { console.log(err) })
    },
    // 新增/编辑属性组
    addAttributeset (type, row) {
      if (type == 'addAttributeset') {
        this.propertyForm = {
          name: '',
          categoryId: "",
        }
        this.dialog.title = '新增属性组'
        this.dialog.type = 'addAttributeset'
        this.dialog.width = '550px'
        this.categoryState = false
        this.dialog.visible = true
        if (this.propName) {
          this.propertyForm.categoryId = this.propName[this.propName.length - 1]
        }
        this.$nextTick(() => {
          this.$refs['propertyForm'].clearValidate()
        })
      } else {
        this.propertyForm = {
          name: '',
          categoryId: "",
        }
        this.categoryState = true
        this.goodsAttrGetGroup(row.propId)
        console.log(row, "编辑属性组row")
        this.dialog.title = '编辑属性组'
        this.dialog.type = 'edit'
        this.dialog.width = '550px'
        this.propId = row.propId
        this.dialog.visible = true
        this.$nextTick(() => {
          this.$refs['propertyForm'].clearValidate()
        })
      }


    },
    // 类目数据
    getCategoryDate () {
      const params = {
        pageSize: 10000,
      }
      this.$api.brandDate(params).then((res) => {
        console.log(res, "类目数据")
        if (res.code == 0) {
          this.categoryOptions = res.data.list
        }
      }).catch((err) => { console.log(err) })
    },
    // 新增属性组弹框所属类目选择值
    handleCategory (e) {
      console.log(e, "选择类目")
      if (e.length > 1) {
        this.propertyForm.categoryId = e[e.length - 1]
      } else {
        this.propertyForm.categoryId = e
      }
    },
    // 添加属性
    addAttribute () {

    },
    attributesetSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialog.type == 'addAttributeset') {
            const data = {
              name: this.propertyForm.name,
              categoryId: this.propertyForm.categoryId.toString()
            }
            this.$api.goodsAttrAddGroup(data).then((res) => {
              if (res.code == 0) {
                this.$message.success('新增成功！')
                this.getDataList(this.dataId)
                this.dialog.visible = false
              }
            }).catch((err) => { console.log(err) })
          }
          else if (this.dialog.type == 'edit') {
            const data = {
              id: this.propId,
              name: this.propertyForm.name,
            }
            this.$api.goodsAttrEditGroup(data).then((res) => {
              if (res.code == 0) {
                this.$message.success('编辑成功！')
                this.getDataList(this.dataId)
                this.dialog.visible = false
              }
            }).catch((err) => { console.log(err) })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    // 新增/编辑属性组提交
    submit (formName) {
      console.log(this.ruleForm, "ruleForm")

      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialog.type == 'propertyEdit') {
            const data = {
              id: this.propertyId,//	是	string	属性组id
              name: this.ruleForm.name,//	是	string	属性名称
              typeFlag: this.ruleForm.typeFlag,//	是	string	属性类型（字典：goods_attr_type）
              requiredFlag: this.ruleForm.requiredFlag,//	是	string	是否必填（0否；1是）
              mainFlag: this.ruleForm.mainFlag,//	是	int	是否关键属性（0否；1是）
              status: this.ruleForm.status,//	是	string	状态（字典分组：enable_status）
              remark: this.ruleForm.remark,//	否	string	备注
              itemList: this.ruleForm.propertyData,//	是	object[]	属性值列表
            }
            this.$api.goodsAttrEdit(data).then((res) => {
              if (res.code == 0) {
                this.$message.success('编辑成功！')
                this.getDataList(this.dataId)
                this.dialog.visible = false
              }
            }).catch((err) => { console.log(err) })
          }
          else if (this.dialog.type == 'add') {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                console.log(this.propertyData, "this.ruleForm.label")
                const data = {
                  goodsGroupId: this.propId,//	是	string	属性组id
                  name: this.ruleForm.name,//	是	string	属性名称
                  typeFlag: this.ruleForm.typeFlag,//	是	string	属性类型（字典：goods_attr_type）
                  requiredFlag: this.ruleForm.requiredFlag,//	是	string	是否必填（0否；1是）
                  mainFlag: this.ruleForm.mainFlag,//	是	int	是否关键属性（0否；1是）
                  status: this.ruleForm.status,//	是	string	状态（字典分组：enable_status）
                  remark: this.ruleForm.remark,//	否	string	备注
                  itemList: this.ruleForm.propertyData ? this.ruleForm.propertyData : null,//	是	object[]	属性值列表
                }
                this.$api.goodsAttrAdd(data).then((res) => {
                  console.log(res, "新增属性数据")
                  if (res.code == 0) {
                    this.$message.success('新增成功！')
                    this.getDataList(this.dataId)
                    this.dialog.visible = false
                  }
                }).catch((err) => { console.log(err) })
              } else {
                console.log('error submit!!');
                return false;
              }
            });

          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });


    },
    goodsAttrGetGroup (id) {
      const params = {
        id: id
      }
      this.$api.goodsAttrGetGroup(params).then(res => {
        if (res.code == 0) {
          console.log(res)
          this.propertyForm.name = res.data.name
          this.propertyForm.categoryId = res.data.categoryList.map((res) => {
            return res.id
          })
          console.log(this.propertyForm.categoryId, "this.propertyForm.categoryId")

        }
      }).catch(err => { console.log(err) })
    },
    // 属性类型选择值
    hangleTypeFlag (e) {
      this.ruleForm.propertyData = []
      console.log(e, "属性类型选择值")
      if (e == 1 || e == 4) {
        this.propertyDataState = 'State'
      } else {
        this.propertyDataState = 'propertyData'
      }
      this.TypeFlagValue = e
      console.log(this.propertyDataState, "this.propertyDataState")
    },
    // 分页
    handleCurrentChange (val) {
      this.pageNo = val;
      console.log(val)
      this.staiffList(this.orgCode);
    },
    handleSizeChange (val) {
      this.pageSize = val;
      this.staiffList(this.orgCode);
    },
    // 属性弹框内表格上移下移
    upMove (index, row) {
      console.log(index, row, "indexx")
      if (index <= 0) {
        this.$message.error('不能继续向上移动')
      } else {
        const upData = this.ruleForm.propertyData[index - 1]
        this.ruleForm.propertyData.splice(index - 1, 1)
        this.ruleForm.propertyData.splice(index, 0, upData)
      }
    },
    // 下移
    upDown (index, row) {
      if (index === (this.ruleForm.propertyData.length - 1)) {
        this.$message.error('不能继续向下移动')
      } else {
        const downData = this.ruleForm.propertyData[index + 1]
        this.ruleForm.propertyData.splice(index + 1, 1)
        this.ruleForm.propertyData.splice(index, 0, downData)
      }
    },
    // 删除
    rowDelete (index) {
      this.ruleForm.propertyData.splice(index, 1);
    },



    // 分页结束
    //**数据请求**//
    treeAxios () {
      const data = {
        orgName: "",
        status: "",
      }
      this.$api.orgTree(data).then(res => {
        console.log(res)
        if (res.code == 0) {
          this.departmentList = res.data;
          this.orgName = res.data[0].orgName;
          this.if_code = false;
          // this.staiffList(res.data[0].orgCode)
        }
      })

    },
    gitDictionaries () {
      const params = {
        groupId: "org_type"
      }
      this.$api.dictionaries(params).then(res => {
        console.log(res, "数据字典")
        this.dictionariesList = res.data
        console.log(this.dictionariesList, 2);
      })
    },
    //**数据请求**//



  }
}
</script>

<style scoped lang="scss">
.div1 {
  margin-left: -16px;
  background: url(../../assets/breadcrumb2.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}

.div2 {
  margin-left: -16px;
  background: url(../../assets/breadcrumb1.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #fff;
}

.div3 {
  margin-left: -8px;
  background: url(../../assets/breadcrumb3.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
/deep/.el-tree-node__label {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.headerbox {
  width: 100%;
  height: 66px;
  background: #fff;
  opacity: 1;
  margin: 10px 0 24px 0;
  display: flex;
  justify-content: space-between;
  padding: 20px;
  box-sizing: border-box;
  font-size: 18px;
  color: #333333;
  font-weight: bold;
  .header {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .title_left {
    width: 4px;
    height: 16px;
    background: #4168e7;
    opacity: 1;
    margin-right: 10px;
  }
}
.el-tree {
  min-height: 580px;
}
.el-menu-vertical-demo {
  width: 200px;
  overflow-y: scroll;
  height: 580px;
}
.el-menu-vertical-demo::-webkit-scrollbar {
  width: 0;
  height: 0;
}

// /deep/.el-input__icon {
//   line-height: 30px;
// }
.demo-ruleForm {
  /deep/input::-webkit-input-placeholder {
    color: #c0c4cc;
    font-size: 10px;
  }

  /deep/input::-moz-input-placeholder {
    color: #c0c4cc;
    font-size: 10px;
  }

  /deep/input::-ms-input-placeholder {
    color: #c0c4cc;
    font-size: 10px;
  }
}
.box {
  display: flex;
  justify-content: flex-start;

  .table_tab {
    margin-left: 20px;
    width: 90%;
  }
}

.demo-form-inline {
  margin-top: 10px;
}

// /deep/.el-input__inner {
//   height: 30px;
//   line-height: 30px;
// }
.el-menu-input {
  padding: 0 15px;
  background: #fff;

  /deep/ .el-input__inner {
    width: 100%;
    height: 30px;
    border: 1px solid #eee;
    margin: 10px 0;
  }
  .titleBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 20px;
    margin-bottom: 8px;
    .division {
      width: 4px;
      height: 16px;
      background: #4c81eb;
      opacity: 1;
      margin-right: 10px;
    }
    .left_title {
      font-family: PingFang SC;
      font-weight: bold;
      color: #333333;
      opacity: 1;
      font-size: 18px;
    }
  }
}
.table {
  margin-top: 10px;
  border-radius: 0;

  /deep/ .el-input--suffix .el-input__inner {
    box-shadow: none;
  }
}
.inquiryTab {
  width: 84%;
  margin-left: 20px;
  background: #fff;
  padding: 10px 20px 20px 20px;
  border-radius: 5px;

  .el-form {
    margin-top: 10px;
  }
  .titleBox {
    display: flex;
    justify-content: space-between;
    margin-top: 5px;

    align-items: center;
    margin-bottom: 11px;

    .left_title {
      font-family: PingFang SC;
      font-weight: bold;
      color: #333333;
      opacity: 1;
    }
  }
}
/deep/.pointer {
  cursor: pointer;
  color: #4c81eb;
}
/deep/.el-dialog {
  border-radius: 10px;
}

/deep/.el-dialog__header {
  border-bottom: 1px solid #d9d9d9;
  padding: 15px 25px 15px;
}
/deep/.el-dialog__title {
  font-family: PingFang SC;
  font-weight: bold;
  color: #333333;
  opacity: 1;
}
/deep/.el-dialog__body {
  padding: 20px 25px;
}
/deep/ .el-table {
  border: 1px solid #e8eaec;
}
/deep/.el-table thead {
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: bold;
  line-height: 22px;
  color: #333333;
  opacity: 1;
}
.addProperty {
  text-align: center;
  border-left: 1px solid #e8eaec;
  border-right: 1px solid #e8eaec;
  border-bottom: 1px solid #e8eaec;
}
.deletegroup {
  /deep/.el-dialog .el-dialog__header {
    background-color: #fff;
  }
  /deep/ .el-dialog__header {
    border: none;
  }
  /deep/.el-dialog__body {
    padding: 0 40px 10px 60px;
  }
}
.hint {
  margin-left: 14px;
  font-size: 12px;
  font-family: PingFang SC;
  font-weight: 400;
  line-height: 0px;
  color: #cccccc;
  opacity: 1;
}
.attributeSet {
  display: flex;
  justify-content: right;
  margin-bottom: 0px;
  .cancel {
    width: 120px;
    height: 36px;
    border: 1px solid #d9d9d9;
    opacity: 1;
    line-height: 0;

    border-radius: 4px;
  }
  .confirm {
    width: 120px;
    height: 36px;
    background: #4168e7;
    line-height: 0;
    opacity: 1;
    margin-left: 14px;
    border-radius: 4px;
  }
}
/deep/.el-table .success-row {
  background: #f5f7fa;
}

/deep/.el-tree-node__content {
  height: 56px;
  font-size: 16px;
}

/deep/.el-tree-node__expand-icon {
  font-size: 18px;
}
.dialogTabel {
  /deep/.el-table thead {
    color: red;
  }
}
/deep/.el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  color: #4168e7;
}
/deep/.el-tree-node__content {
  &:hover {
    background-color: #f0f7ff;
    color: #4168e7;
  }
}
</style>
